package com.ambitor.grass.sql.dao.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

import com.ambitor.grass.sql.dao.BaseDao;
import com.ambitor.grass.sql.dao.MetaDataDao;

public class MetaDataDaoImpl implements MetaDataDao {

	private Connection conn;
	BaseDao baseDao;

	public MetaDataDaoImpl(Connection conn) {
		this.conn = conn;
		baseDao = new BaseDaoImpl(conn);
	}

	public ResultSetMetaData getMetaData(String tableName) throws Exception {
		String sql = "select * from " + tableName.toUpperCase()
				+ " where 1 = 0";
		ResultSet rs = baseDao.executeQuery(sql);
		ResultSetMetaData metaData = rs.getMetaData();
		rs.close();
		return metaData;
	}

	@SuppressWarnings("unchecked")
	public String[] getPrimaryKeys(String tableName) throws Exception {
		ResultSet rs = conn.getMetaData().getPrimaryKeys(null, "%",
				tableName.toUpperCase());
		List keys = new ArrayList();
		while (rs.next()) {
			String columName = rs.getString("COLUMN_NAME").toUpperCase();
			keys.add(columName);
		}
		rs.close();
		return (String[]) (keys.toArray(new String[0]));
	}
}
